import React, { Component } from 'react'
import {
    Card,
    Button,
    Table,
    Modal,
    message,
} from "antd"
import {PAGE_SIZE} from "../../utils/constants" 
import { reqRoles, reqAddRole, reqUpdateRole} from '../../api';
import AddForm from './AddForm';
import AuthForm from './AuthForm'; 
import memoryUtils from '../../utils/memoryUtils';
import storageUtils from '../../utils/storageUtils';


/*
    角色管理路由
*/
export default class Role extends Component {
    constructor(props) {
        super(props)
        this.initColumn();
    }

    myAuth = React.createRef()

    state = {
        roles: [], // 所有角色的列表
        role:{}, //选中的role
        isShowAdd: false, // 是否显示添加界面
        isShowSet: false, // 是否显示设置角色权限界面
    }
    
    // 添加角色
    addRole = () => {
        this.setState({isShowAdd: false})

        this.myAddForm.current.validateFields()
        .then(async values => {
            const {roleName} = values;
            const result = await reqAddRole(roleName)
            if(result.status === 0) {
                message.success("添加角色成功")
                // 新产生的角色
                const role = result.data;
                // 更新roles状态 : k
                this.setState( state => ({
                    roles : [...state.roles, role]
                }))
            } else {
                message.error("添加角色失败")
            }
        })
        .catch(error => {
            message.error("添加角色失败,原因",error)
        })
        
    }

    // 设置角色权限
    setRoleAuthority = async() => {
        this.setState({isShowSet: false})

        const role = this.state.role;
        // 得到最新的menus
        const menus = this.myAuth.current.getMenus()
        role.menus = menus

        // 请求更新
        const result = await reqUpdateRole(role)
        if(result.status === 0) {  
            // 如果当前更新的是自己角色的权限, 强制退出
            if(role._id === memoryUtils.user.role_id) {
                memoryUtils.user = {} // 将用户信息清空
                storageUtils.removeUser() // 删除本地信息
                this.props.history.replace("/login")
                message.info("当前用户角色权限已更新,请重新登录!")
            } else {
                message.success("设置权限成功")
                this.setState({
                    roles: [...this.state.roles]
                })
            }
            
        } else {
            message.error("设置权限失败")
        }

    }


    getRoles = async () => {
        const result = await reqRoles();
        if(result.status === 0) {
            const roles = result.data
            this.setState({roles})
        }
    }


    initColumn = () => {
        this.columns = [
            {
                title: "角色名称" ,
                dataIndex:"name"
            },
            {
                title: "创建时间" ,
                dataIndex:"create_time"
            },
            {
                title: "授权时间" ,
                dataIndex:"auth_time"
            },
            {
                title: "授权人" ,
                dataIndex:"auth_name"
            },
        ]
    }

    onRow = (role) => {
        return {
            onClick: event => { // 点击行
                this.setState({role})
            }
        }
    }

    componentDidMount() {
        this.getRoles()
    }

    render() {
        const {roles, role, isShowAdd, isShowSet} = this.state

        const title = (
            <span>
                <Button type="primary" onClick={() => this.setState({isShowAdd: true})}>创建角色</Button> &nbsp;
                <Button type="primary" disabled={!role._id} onClick={() => this.setState({isShowSet: true})}>设置角色权限</Button>
            </span>
        )
        return (
            <Card title={title}>
                <Table
                    bordered
                    rowKey="_id" 
                    dataSource={roles}
                    columns={this.columns}
                    pagination={{defaultPageSize: PAGE_SIZE}}
                    rowSelection={{type: 'radio', 
                        selectedRowKeys: [role._id], 
                        onChange: (_, selectedRows) => {
                            this.setState({role:selectedRows[0]})
                        }
                    }}  
                    onRow={this.onRow}
                />
                
                <Modal 
                    title="添加角色" 
                    visible={isShowAdd} 
                    onOk={this.addRole} 
                    onCancel={() => this.setState({isShowAdd:false})}
                    destroyOnClose={true}
                >
                    <AddForm
                        setAddForm={(myAddForm) => this.myAddForm = myAddForm}
                    />
                </Modal>

                <Modal 
                    title="设置角色权限" 
                    visible={isShowSet} 
                    onOk={this.setRoleAuthority} 
                    onCancel={() => this.setState({isShowSet:false})}
                    destroyOnClose={true}
                >
                    <AuthForm 
                        role={role}
                        ref={this.myAuth}
                    />
                </Modal>    
            </Card>
        )
    }
}
